/* gap.c, Ait, BSD 3-Clause, Kevin Bloom, 2023-2025,
   Derived from: Atto January 2017
   Derived from: Anthony's Editor January 93
*/

#include <sys/stat.h>
#include "header.h"
#include "util.h"

/* Enlarge gap by n chars, position of gap cannot change */
int growgap(buffer_t *bp, point_t n)
{
  char_t *new;
  point_t buflen, newlen, xgap, xegap;

  assert(bp->b_buf <= bp->b_gap);
  assert(bp->b_gap <= bp->b_egap);
  assert(bp->b_egap <= bp->b_ebuf);

  xgap = bp->b_gap - bp->b_buf;
  xegap = bp->b_egap - bp->b_buf;
  buflen = bp->b_ebuf - bp->b_buf;

  /* reduce number of reallocs by growing by a minimum amount */
  n = (n < MIN_GAP_EXPAND ? MIN_GAP_EXPAND : n);
  newlen = buflen + n * sizeof (char_t);

  if (buflen == 0) {
    if (newlen < 0 || MAX_SIZE_T < newlen)
      fatal("%s: Failed to allocate required memory.\n");
    new = (char_t*) malloc((size_t) newlen);
    if (new == NULL)
      fatal("%s: Failed to allocate required memory.\n");  /* Cannot edit a file without a buffer. */
  } else {
    if (newlen < 0 || MAX_SIZE_T < newlen) {
      msg("Failed to allocate required memory");
      return (FALSE);
    }
    new = (char_t*) realloc(bp->b_buf, (size_t) newlen);
    if (new == NULL) {
      msg("Failed to allocate required memory");    /* Report non-fatal error. */
      return (FALSE);
    }
  }

  /* Relocate pointers in new buffer and append the new
   * extension to the end of the gap.
   */
  bp->b_buf = new;
  bp->b_gap = bp->b_buf + xgap;
  bp->b_ebuf = bp->b_buf + buflen;
  bp->b_egap = bp->b_buf + newlen;
  while (xegap < buflen--)
    *--bp->b_egap = *--bp->b_ebuf;
  bp->b_ebuf = bp->b_buf + newlen;

  assert(bp->b_buf < bp->b_ebuf);          /* Buffer must exist. */
  assert(bp->b_buf <= bp->b_gap);
  assert(bp->b_gap < bp->b_egap);          /* Gap must grow only. */
  assert(bp->b_egap <= bp->b_ebuf);
  return (TRUE);
}

point_t movegap(buffer_t *bp, point_t offset)
{
  char_t *p = ptr(bp, offset);
  while (p < bp->b_gap)
    *--bp->b_egap = *--bp->b_gap;
  while (bp->b_egap < p)
    *bp->b_gap++ = *bp->b_egap++;
  assert(bp->b_gap <= bp->b_egap);
  assert(bp->b_buf <= bp->b_gap);
  assert(bp->b_egap <= bp->b_ebuf);
  return (pos(bp, bp->b_egap));
}

/* Given a buffer offset, convert it to a pointer into the buffer */
char_t * ptr(buffer_t *bp, register point_t offset)
{
  if (offset < 0)
    return (bp->b_buf);
  return (bp->b_buf+offset + (bp->b_buf + offset < bp->b_gap ? 0 : bp->b_egap-bp->b_gap));
}

/* Given a pointer into the buffer, convert it to a buffer offset */
point_t pos(buffer_t *bp, register char_t *cp)
{
  assert(bp->b_buf <= cp && cp <= bp->b_ebuf);
  return (cp - bp->b_buf - (cp < bp->b_egap ? 0 : bp->b_egap - bp->b_gap));
}

int posix_file(char *fn)
{
  if (fn[0] == '_')
    return (FALSE);

  for (; *fn != '\0'; ++fn) {
    if (!isalnum((int)*fn) && *fn != '.' && *fn != '_' && *fn != '-' && *fn != '/')
      return (FALSE);
  }
  return (TRUE);
}

void relocate_backup(char *fp)
{
  char ltemp[PATH_MAX+2];
  strcpy(ltemp, fp);
  replace_all(ltemp, '/', '!');
  strcpy(fp, backup_dir);
  strcat(fp, ltemp);
}

/*
   This code is heavily based on OpenBSD's mg(1)
   See mg's `fileio.c` file.
*/
int backup_file(char *fn)
{
  int orig, backup;
  char bfn[PATH_MAX+2];
  char *tname;
  char buf[STRBUF_L];
  struct stat sb;
  ssize_t nread;
  struct timespec new_times[2];

  sprintf(bfn, "%s~", fn);
  if(backup_dir != NULL)
    relocate_backup(bfn);
  /* If we can't open the original, just don't make a back up */
  if (stat(fn, &sb) == -1) {
    msg("Can't stat %s : %s", fn, strerror(errno));
    return TRUE;
  }
  if((orig = open(fn, O_RDONLY)) == -1) {
    return TRUE;
  }
  if (asprintf(&tname, "%s.XXXXXXXXXX", bfn) == -1) {
    msg("Can't allocate temp file name : %s", strerror(errno));
    return FALSE;
  }
  backup = mkstemp(tname);
  if(backup == -1) {
    msg("Failed to open backup file: \"%s\"", bfn);
    return FALSE;
  }
  while ((nread = read(orig, buf, sizeof(buf))) > 0) {
    if (write(backup, buf, (size_t)nread) != nread) {
      nread = -1;
      break;
    }
  }
  (void) fchmod(backup, (sb.st_mode & 0777));
  new_times[0] = sb.st_atim;
  new_times[1] = sb.st_mtim;
  futimens(backup, new_times);
  close(orig);
  close(backup);
  if (nread == -1) {
    if (unlink(tname) == -1)
      msg("Can't unlink temp : %s", strerror(errno));
  } else {
    if (rename(tname, bfn) == -1) {
      msg("Can't rename temp : %s", strerror(errno));
      (void) unlink(tname);
      nread = -1;
    }
  }
  return (nread == -1 ? FALSE : TRUE);
}

int save(char *fn)
{
  FILE *fp;
  point_t length;
  struct stat sb;

//  if (!posix_file(fn)) {
//    msg("Not a portable POSIX file name.");
//    return (FALSE);
//  }
  stat(fn, &sb);
  if (!backup_file(fn)) {
//    msg("Failed to backup file \"%s\".", fn);
    return (FALSE);
  }
  fp = fopen(fn, "w");
  if (fp == NULL) {
    msg("Failed to open file \"%s\".", fn);
    return (FALSE);
  }
  (void) movegap(curbp, (point_t) 0);
  length = (point_t) (curbp->b_ebuf - curbp->b_egap);
  if (fwrite(curbp->b_egap, sizeof (char), (size_t) length, fp) != length) {
    msg("Failed to write file \"%s\".", fn);
    return (FALSE);
  }
  if (fclose(fp) != 0) {
    msg("Failed to close file \"%s\".", fn);
    return (FALSE);
  }
  curbp->b_flags &= ~B_MODIFIED;
  if (stat(fn, &sb) < 0) {
    msg("Failed to find file \"%s\".", fn);
    return (FALSE);
  }
  if (MAX_SIZE_T < sb.st_size) {
    msg("File \"%s\" is too big to load.", fn);
    return (FALSE);
  }
  curbp->b_fmtime = sb.st_mtime;
  msg("File \"%s\" %ld bytes saved.", fn, pos(curbp, curbp->b_ebuf));
  return (TRUE);
}

int load_file(char *fn)
{
  /* reset the gap, make it the whole buffer */
  curbp->b_gap = curbp->b_buf;
  curbp->b_egap = curbp->b_ebuf;
  top();
  return insert_file(fn, FALSE);
}

/* reads file into buffer at point */
int insert_file(char *fn, int modflag)
{
  FILE *fp;
  size_t len;
  struct stat sb;

  if (stat(fn, &sb) < 0) {
    msg("Failed to find file \"%s\".", fn);
    return (FALSE);
  }
  if (MAX_SIZE_T < sb.st_size) {
    msg("File \"%s\" is too big to load.", fn);
    return (FALSE);
  }
  if (curbp->b_egap - curbp->b_gap < sb.st_size * sizeof (char_t) && !growgap(curbp, sb.st_size))
    return (FALSE);
  if ((fp = fopen(fn, "r")) == NULL) {
    msg("Failed to open file \"%s\".", fn);
    return (FALSE);
  }
  curbp->b_point = movegap(curbp, curbp->b_point);
  curbp->b_gap += len = fread(curbp->b_gap, sizeof (char), (size_t) sb.st_size, fp);
  if (fclose(fp) != 0) {
    msg("Failed to close file \"%s\".", fn);
    return (FALSE);
  }
  curbp->b_flags &= (modflag ? B_MODIFIED : ~B_MODIFIED);
  if(!modflag)
    curbp->b_fmtime = sb.st_mtime;
  msg("%ld bytes read.", len);
  return (TRUE);
}

/* Record a new undo */
void undoset(int type, int shouldconcat)
{
  int length = strlen((const char *)input);
  int npc = 0;
  char_t *p, *utemp, *dtemp;
  undo_t *u = (undo_t *)malloc(sizeof(undo_t));
  assert(u != NULL);
  u->u_type = type;
  u->u_point = curbp->b_point;
  u->u_line = curbp->b_line;
  u->u_adjust = FALSE;
  u->u_data = NULL;
  switch(type) {
    case INSERT:
      if(curbp->b_undo != NULL && curbp->b_undo->u_type == INSERT && shouldconcat) {
        asprintf((char **)&utemp, "%s%s", curbp->b_undo->u_data, input);
        free(curbp->b_undo->u_data);
        curbp->b_undo->u_data = utemp;
        return;
      } else {
        asprintf((char **)&u->u_data, "%s", input);
      }
      break;
    case DELETE:
      if(curbp->b_buf == NULL)
        return;
      npc = utf8_size(*ptr(curbp,curbp->b_point));
      if(curbp->b_undo != NULL && curbp->b_undo->u_type == DELETE && shouldconcat) {
        dtemp = (char_t *) strndup((const char *)ptr(curbp, curbp->b_point), npc);
        asprintf((char **)&utemp, "%s%s", curbp->b_undo->u_data, dtemp);
        free(curbp->b_undo->u_data);
        curbp->b_undo->u_data = utemp;
        free(dtemp);
        dtemp = NULL;
        return;
      } else if(npc > 0) {
        u->u_data = (char_t *)(malloc(npc+1));
        memcpy(u->u_data, ptr(curbp, curbp->b_point), npc);
        u->u_data[npc] = '\0';
      }
      break;
    case BACKSP:
      if(curbp->b_buf == NULL)
        return;
      npc = prev_utf8_char_size();
      if(curbp->b_undo != NULL && curbp->b_undo->u_type == BACKSP && shouldconcat) {
         curbp->b_undo->u_point -= npc;
         dtemp = (char_t *)malloc(npc+1);
         (void) memcpy(dtemp, ptr(curbp, curbp->b_undo->u_point), npc);
         dtemp[npc] = '\0';
         asprintf((char **)&utemp, "%s%s", dtemp, curbp->b_undo->u_data);
         free(curbp->b_undo->u_data);
         curbp->b_undo->u_data = utemp;
         free(dtemp);
         dtemp = NULL;
         return;
      } else {
        u->u_point = curbp->b_point - npc;
        u->u_data = (char_t *)(malloc(npc+1));
        strncpy((char *)u->u_data, (const char *)ptr(curbp, u->u_point), npc);
        u->u_data[npc] = '\0';
        u->u_adjust = TRUE;
      }
      break;
    case CUT: {
      int bigger_mark = FALSE;
        if (curbp->b_point < curbp->b_mark) {
          (void) movegap(curbp, curbp->b_point);
          p = ptr(curbp, curbp->b_point);
          length = curbp->b_mark - curbp->b_point;
          bigger_mark = TRUE;
          u->u_adjust = TRUE;
        } else {
          (void) movegap(curbp, curbp->b_mark);
          p = ptr(curbp, curbp->b_mark);
          length = curbp->b_point - curbp->b_mark;
          u->u_point = curbp->b_mark;
        }
      if(curbp->b_undo != NULL &&
         curbp->b_undo->u_type == CUT &&
         shouldconcat) {
        dtemp = malloc(length+1);
        memcpy(dtemp, p, length);
        dtemp[length] = '\0';
        if(shouldconcat < 0) {
          asprintf(
            (char **)&utemp,
            "%s%s", dtemp, curbp->b_undo->u_data
          );
          curbp->b_undo->u_point = curbp->b_point;
        } else
          asprintf(
            (char **)&utemp,
            "%s%s", curbp->b_undo->u_data, dtemp
          );
        if(curbp->b_undo->u_data != NULL)
          free(curbp->b_undo->u_data);
        curbp->b_undo->u_data = utemp;
        curbp->b_undo->u_size = length+curbp->b_undo->u_size;
        /* Only adjust u_adjust if it's not a delete word command,
           otherwise the line count will be off.
        */
        if(currentcommand != KBD_DELETE_WORD)
          for(int i = 0; curbp->b_undo->u_data[i] != '\0'; i++) {
            if(curbp->b_undo->u_data[i] == '\n') {
              curbp->b_undo->u_adjust = !bigger_mark;
              break;
            }
        }
        free(dtemp);
        return;
      } else {
        u->u_data = (char_t*) malloc(length+1);
        (void) memcpy(u->u_data, p, length);
        u->u_data[length] = '\0';
        u->u_size = length;
        /* Only adjust u_adjust if it's not a delete word command,
           otherwise the line count will be off.
        */
        if(currentcommand != KBD_DELETE_WORD)
          for(int i = 0; u->u_data[i] != '\0'; i++) {
            if(u->u_data[i] == '\n') {
              u->u_adjust = !bigger_mark;
              break;
            }
          }
      }
      break;
    }
    case YANK:
      u->u_data = (char_t *) strndup((const char *)scrap.data, scrap.len);
      u->u_data[scrap.len] = '\0';
      break;
    case REPLACE:
      (void) movegap(curbp, curbp->b_point);
      p = ptr(curbp, curbp->b_point);
      length = curbp->b_mark - curbp->b_point;
      u->u_data = (char_t*) malloc(length+1);
      (void) memcpy(u->u_data, p, length);
      u->u_data[length] = '\0';
      u->u_size = shouldconcat;
      break;
    case CLIPBOARD: {
      int ntemp = strlen(gtemp);
      u->u_data = (char_t*) malloc(ntemp+1);
      (void) memcpy(u->u_data, gtemp, ntemp);
      u->u_data[ntemp] = '\0';
      break;
    }
    case LOAD: {
      (void) movegap(curbp, (point_t) 0);
      u->u_data = (char_t*) malloc(curbp->b_size+1);
      (void) memcpy(u->u_data, curbp->b_egap, curbp->b_size);
      u->u_data[curbp->b_size] = '\0';
      u->u_size = curbp->b_size;
      break;
    }
  }
  u->u_next = curbp->b_undo;
  curbp->b_undo = u;
  curbp->b_redo = NULL;
}

/* Record a new redo if you've just undid or a undo if you've just redid. */
void redo_or_undo_set(undo_t *up, int datalen, int isundo)
{
  undo_t *rp = (undo_t *)malloc(sizeof(undo_t));
  char_t *p;
  int newlines = 0;
  assert(rp != NULL);
  rp->u_point = up->u_point;
  rp->u_line = up->u_line;
  if(up->u_adjust)
  for(int i = 0 ; up->u_data[i] != '\0'; i++) {
    if(up->u_data[i] == '\n')
      newlines++;
  }
  switch(up->u_type) {
  case INSERT:
    rp->u_type = DELETE;
    break;
  case BACKSP:
    rp->u_adjust = TRUE;
    rp->u_line -= newlines;
  case DELETE:
    rp->u_type = INSERT;
    break;
  case CUT:
    rp->u_type = YANK;
    rp->u_line -= newlines;
    break;
  case CLIPBOARD:
  case YANK:
    rp->u_type = CUT;
    rp->u_line += newlines;
    break;
  case REPLACE:
    rp->u_type = REPLACE;
    (void) movegap(curbp, up->u_point);
    p = ptr(curbp, up->u_point);
    rp->u_data = (char_t*) malloc(up->u_size+1);
    (void) memcpy(rp->u_data, p, up->u_size);
    rp->u_data[up->u_size] = '\0';
    rp->u_size = datalen;
    break;
  case LOAD:
    rp->u_type = LOAD;
    (void) movegap(curbp, (point_t) 0);
    rp->u_data = (char_t*) malloc(curbp->b_size+1);
    (void) memcpy(rp->u_data, curbp->b_egap, curbp->b_size);
    rp->u_data[curbp->b_size] = '\0';
    rp->u_size = curbp->b_size;
    break;
  }
/*  if(rp != NULL && rp->u_data != NULL && rp->u_type != REPLACE)  {
    free(rp->u_data);
    rp->u_data = NULL;
  } */
  if(rp->u_type != REPLACE && rp->u_type != LOAD) {
    rp->u_data = (char_t *) calloc(datalen+1, sizeof(char_t));
    (void) memcpy(rp->u_data, up->u_data, datalen);
    rp->u_data[datalen] = '\0';
  }
  /* if an undo was done, save to redo */
  if(isundo) {
    rp->u_next = curbp->b_redo;
    curbp->b_redo = rp;
  } else {
    rp->u_next = curbp->b_undo;
    curbp->b_undo = rp;
  }
}

/* Undo */
void undo_or_redo(buffer_t *bp, undo_t *up, int isundo)
{
  int n = 0;
  currentcommand = KBD_UNDO;
  if(up == NULL) {
    if(isundo)
      msg("Nothing to undo!");
    else
      msg("Nothing to redo!");
  return;
  }
  bp->b_point = up->u_point;
  bp->b_line = up->u_line;
  n = strlen((const char *)up->u_data);
  redo_or_undo_set(up, n, isundo);
  switch(up->u_type) {
  case INSERT:
  case YANK:
  case CLIPBOARD:
    (void) movegap(bp, bp->b_point);
    bp->b_egap += n;
    bp->b_point = pos(bp, bp->b_egap);
    break;
  case BACKSP:
  case DELETE:
  case CUT:
    bp->b_point = movegap(bp, bp->b_point);
    memcpy(bp->b_gap, up->u_data, n);
    bp->b_gap += n;
    bp->b_point = pos(bp, bp->b_egap);
    break;
  case REPLACE:
    (void) movegap(bp, bp->b_point);
    bp->b_egap += up->u_size;
    bp->b_point = pos(bp, bp->b_egap);
    bp->b_point = movegap(bp, bp->b_point);
    memcpy(bp->b_gap, up->u_data, n);
    bp->b_gap += n;
    bp->b_point = pos(bp, bp->b_egap);
    break;
  case LOAD: {
    bp->b_gap = bp->b_buf;
    bp->b_egap = bp->b_ebuf;
    (void) movegap(bp, 0);
    if (bp->b_egap - bp->b_gap < up->u_size * sizeof (char_t))
      (void) growgap(bp, up->u_size);
    bp->b_point = movegap(bp, bp->b_point);
    memcpy(bp->b_gap, up->u_data, up->u_size);
    bp->b_gap += up->u_size;
    bp->b_point = pos(bp, bp->b_egap);
    bp->b_line = 1;
    break;
  }
  }

  if(up->u_adjust && isundo)
    bp->b_point = movegap(bp, up->u_point + n);
  else
    bp->b_point = movegap(bp, up->u_point);
  bp->b_flags |= B_MODIFIED;

  if(isundo)
    bp->b_undo = up->u_next;
  else
    bp->b_redo = up->u_next;

  if(curbp->b_point < curbp->b_page || curbp->b_point > curbp->b_epage)
    bp->b_reframe = 1;
}

void undo()
{
  undo_or_redo(curbp, curbp->b_undo, TRUE);
}

/* Redo */
void redo()
{
  undo_or_redo(curbp, curbp->b_redo, FALSE);
}



/* find the point for start of line ln */
point_t line_to_point(int ln)
{
  point_t end_p = pos(curbp, curbp->b_ebuf);
  point_t p, start;
  for (p=0, start=0; p <= end_p; p++) {
    char_t *c = ptr(curbp, p);
    if(c == 0)
      break;
    if ( *c == '\n') {
      if (--ln == 0)
        return start;
      if (p + 1 <= end_p)
        start = p + 1;
    }
    if(!*c && ln == 1)
      return start;
  }
  return -1;
}

/* scan buffer and fill in curline and lastline */
void get_line_stats(int *curline, int *lastline, buffer_t *bp)
{
  point_t end_p = pos(bp, bp->b_ebuf);
  point_t p;
  int line;

  *curline = -1;

  for (p=0, line=0; p < end_p; p++) {

    line += (*(ptr(bp,p)) == '\n') ? 1 : 0;
    *lastline = line;

    if (*curline == -1 && p == bp->b_point) {
      *curline = (*(ptr(bp,p)) == '\n') ? line : line + 1;
    }
  }

  *lastline = *lastline + 1;

  if (bp->b_point == end_p)
    *curline = *lastline;
}

/* Return TRUE if file was modified after the current buffer's recored mtime. */
int is_file_modified(char *fn)
{
  struct stat sb;
  if(stat(fn, &sb) < 0) {
    return (FALSE);
  }
  if(sb.st_mtime != 0 && curbp->b_fmtime != sb.st_mtime) {
    return (TRUE);
  }
  return (FALSE);
}

/* Return TRUE to continue, FALSE to stop. Revert happens here. */
int file_was_modified_prompt()
{
  int current = 0, lastln = 0;
  const char *prompt = "This file has changed on disk; really edit (y/N/r) ?";
  int size = strlen(prompt);
  char c = '\0';
  point_t p = curbp->b_point;
  struct stat sb;
  print_to_msgline(prompt);
  clrtoeol(size, MSGLINE);
  c = yesnomaybeso('n');
  if (c == 'n') {
    clrtoeol(0, MSGLINE);
    return FALSE;
  } else if(c == 'r') {
    curbp->b_point = 0;
    undoset(LOAD, FALSE);
    load_file(curbp->b_fname);
    clrtoeol(0, MSGLINE);
    curbp->b_point = p;
    get_line_stats(&current, &lastln, curbp);
    curbp->b_line = current;
    msg("Buffer reverted.");
    return FALSE;
  } else if(c == 'y') {
    clrtoeol(0, MSGLINE);
    if (stat(curbp->b_fname, &sb) < 0) {
      msg("Failed to find file \"%s\".", curbp->b_fname);
      return (FALSE);
    }
    if (MAX_SIZE_T < sb.st_size) {
      msg("File \"%s\" is too big to load.", curbp->b_fname);
      return (FALSE);
    }
    curbp->b_fmtime = sb.st_mtime;
    return TRUE;
  }
  clrtoeol(0, MSGLINE);
  return (FALSE);
}
